package eteam.aps.controller;

import eteam.aps.common.R;
import eteam.aps.common.component.LoginUserRedisService;
import eteam.aps.common.entity.ParentEntity;
import eteam.aps.common.exceptions.AuthException;
import eteam.aps.common.exceptions.BusinessException;
import eteam.aps.common.helper.Helper;
import eteam.aps.common.helper.JsonPage;
import eteam.aps.model.entity.Worksheet;
import eteam.aps.model.vo.WorksheetVo;
import eteam.aps.service.QueryInfoService;
import eteam.aps.service.WorksheetService;
import eteam.aps.systeminterface.model.dto.VerifyTokenDto;
import eteam.aps.systeminterface.model.vo.QueryInfoVo;
import eteam.aps.systeminterface.model.vo.Worksheets;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 单据流水号控制层
 *
 * @author WMT
 * @Date 2023/2/17 14:17
 */
@Api(tags = "单据流水号模块")
@RestController
public class WorksheetController implements IWorksheetController {

    @Autowired
    private WorksheetService worksheetService;

    @Autowired
    private QueryInfoService queryInfoService;

    @Autowired
    private LoginUserRedisService loginUserRedisService;

    @Override
    @ApiOperation("添加单据流水号")
    @PostMapping("/work/insert")
    public R<Integer> insert(@RequestBody Worksheet worksheet) throws Exception, AuthException {
        VerifyTokenDto user = loginUserRedisService.getUser();
        worksheet.setfId(Helper.GetId());
        worksheet.setfState(ParentEntity.FSTATE_DRAFT);
        worksheet.setfCreateUserId(user.getFuserid());
        worksheet.setfLastModifyUserId(user.getFuserid());
        worksheet.setfBookCode(user.getFgrouporgid());
        LocalDateTime now = LocalDateTime.now();
        worksheet.setfCreatorTime(now);
        worksheet.setfLastModifyTime(now);

        Map<String, Object> map = new HashMap<>(2);
        map.put("worksheetCode",worksheet.getfWorksheetCode());
        map.put("fSystemId",worksheet.getfSystemId());
        if (worksheetService.selectCountWorksheetCode(map) > 0){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"单据编号已存在！");
        }
        map.clear();
        map.put("worksheetName",worksheet.getfWorksheetName());
        map.put("fSystemId",worksheet.getfSystemId());
        if (worksheetService.selectCountWorksheetName(map) > 0){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"单据名称已存在！");
        }
        if (worksheet.getfStreamLength() > 5){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"流水号长度不能大于5位！");
        }

        int useDate = worksheet.getfUseDate();
        String prefix = worksheet.getfPrefix();
        if (prefix.length() > 6){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"单据前缀太长");
        }
        if(worksheet.getfRozone() == Worksheet.FROZONE_TRUE){
            worksheet.setfRozone((int) ((Math.random() * 9 + 1) * 100000));
        }
        String date = "";
        String year = String.valueOf(now.getYear());
        String month = String.valueOf(now.getMonth().getValue());
        if (month.length() < 2){
            month = year + "0" + month;
        }
        String day = String.valueOf(now.getDayOfMonth());
        if (day.length() < 2){
            day = month + "0" + day;
        }
        if (worksheet.getfAutoNo() == Worksheet.FAUTONO_TRUE) {
            switch (useDate) {
                case Worksheet.FUSEDATE_TYEAR:
                    date += year;
                    break;
                case Worksheet.FUSEDATE_MONTH:
                    date += month;
                    break;
                case Worksheet.FUSEDATE_DAY:
                    date += day;
                    break;
                default:
                    break;
            }
            prefix += date;
        }
        worksheet.setfPrefix(prefix);
        return R.success(worksheetService.insert(worksheet));
    }

    @Override
    @ApiOperation("删除单据流水号")
    @PostMapping("/work/delete/{fId}")
    public R<Integer> delete(@PathVariable String fId) throws Exception, AuthException {
        if (Helper.isEmpty(fId)){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"fId不能为空");
        }
        return R.success(worksheetService.delete(fId));
    }

    @Override
    @ApiOperation("修改单据流水号")
    @PostMapping("/work/update")
    public R<Integer> update(@RequestBody Worksheet worksheet) throws Exception, AuthException {
        VerifyTokenDto user = loginUserRedisService.getUser();
        worksheet.setfLastModifyUserId(user.getFuserid());
        worksheet.setfLastModifyTime(LocalDateTime.now());

        if (Helper.isEmpty(worksheet.getfId())){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"fId不能为空");
        }
        return R.success(worksheetService.update(worksheet));
    }

    @Override
    @ApiOperation("分页查询单据流水号")
    @PostMapping("/work/selectAll")
    public R<JsonPage<WorksheetVo>> selectAll(
            @RequestParam("fSystemId") Integer fSystemId,
            @RequestParam(value = "fWorksheetName",required = false) String fWorksheetName,
            @RequestParam(value = "fWorksheetCode",required = false) String fWorksheetCode,
            @RequestParam("page") Integer page,@RequestParam("pageSize") Integer pageSize
    ) throws Exception, AuthException {
        Map<String, Object> map = new HashMap<>(3);
        map.put("fSystemId",fSystemId);
        if (Helper.isNotEmpty(fWorksheetCode)){
            map.put("fWorksheetCode",Helper.likeSql(fWorksheetCode));
        }
        if (Helper.isNotEmpty(fWorksheetName)){
            map.put("fWorksheetName",Helper.likeSql(fWorksheetName));
        }
        JsonPage<WorksheetVo> jsonPage = worksheetService.selectAll(map, Helper.valuePositive(page, 1),
                Helper.valuePositive(pageSize, 10));
        List<WorksheetVo> list = jsonPage.getList();
        if (list != null){
            list.forEach(
                    worksheetVo -> {
                        worksheetVo.setfCreateUserName(queryInfoService.selectUserName().get(worksheetVo.getfCreateUserId()));
                        worksheetVo.setfWorksheetTypeName(queryInfoService.selectDdName().get(worksheetVo.getfWorksheetType()));
                    }
            );
        }
        return R.success(jsonPage);
    }

    @Override
    @ApiOperation("查询单据类型列表")
    @PostMapping("/work/sheetTypeList/{order}")
    public R<List<QueryInfoVo>> sheetTypeList(@PathVariable int order) throws Exception, AuthException {
        return R.success(worksheetService.selectTypeByOrder(order));
    }

    @Override
    @ApiOperation("查询单据流水号详情")
    @PostMapping("/work/selectDetails/{fId}")
    public R<WorksheetVo> selectDetails(@PathVariable String fId) throws Exception, AuthException {
        WorksheetVo worksheetVo = worksheetService.selectDetails(fId);
        if (worksheetVo == null){
            throw new BusinessException(HttpStatus.BAD_REQUEST,"fId不存在");
        }
        worksheetVo.setfWorksheetTypeName(queryInfoService.selectDdName().get(worksheetVo.getfWorksheetType()));
        worksheetVo.setfCreateUserName(queryInfoService.selectUserName().get(worksheetVo.getfCreateUserId()));
        return R.success(worksheetVo);
    }

    @Override
    @PostMapping("/work/selectSheetPrefix/{sheetCode}")
    public Worksheets selectSheetPrefix(@PathVariable String sheetCode) throws Exception, AuthException {
        return worksheetService.selectSheetPrefix(sheetCode);
    }

    @Override
    @PostMapping("/work/selectDdByWorksheetType")
    public List<QueryInfoVo> selectDdByWorksheetType() throws Exception, AuthException {
        return worksheetService.selectDdByWorksheetType();
    }


    @Override
    public QueryInfoVo selectCodeByWorksheetName(String name) throws Exception, AuthException {
        return worksheetService.selectCodeByWorksheetName(name);
    }


    @Override
    public QueryInfoVo selectNameByCode(String code) throws Exception, AuthException {
        return worksheetService.selectNameByCode(code);
    }
}
